/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package interfaz;

import clases.ClsContraladorEventos;
import clases.ClsDatabase;
import clases.ClsMetodos;
import java.awt.Image;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;

/**
 *
 * @author ser
 */
public class dlgIndiceEditar extends javax.swing.JDialog {

    private ClsDatabase bd = new ClsDatabase();
    DefaultComboBoxModel modelpartidacodigo = new DefaultComboBoxModel();
    DefaultComboBoxModel modelCboUnidad = new DefaultComboBoxModel();
    ClsContraladorEventos controlEvent = new ClsContraladorEventos();
//    private ClsSeguridad seguridad = new ClsSeguridad();
//    private ClsSesion sesion = new ClsSesion();
    private ClsMetodos metodos = new ClsMetodos();
    DefaultComboBoxModel modelCboTipoInsumo = new DefaultComboBoxModel();
    String nivel_codigo = "", raiz_1 = "";
    int opcion = 1;

    /** 
     * Creates new form dlgPartidaPrecioModifica
     */
    public dlgIndiceEditar(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

    }
 
    public dlgIndiceEditar(java.awt.Frame parent, boolean modal, String codigo, String descripcion, String nivel_cod, int opcion) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);
        Image image = new ImageIcon(getClass().getResource("/resource/icon/principales/Logo.png")).getImage();

        //Para poner Icon en un JDialog
        ((java.awt.Frame) this.getOwner()).setIconImage(image);
        nivel_codigo = nivel_cod;
        raiz_1 = codigo;
        this.opcion = opcion;
        txtDentroDe.setText(descripcion);
        txtNombre.requestFocus();
        //jTextField2.setText();
        if(opcion==2){
            jLabel2.setVisible(false);
            txtDentroDe.setVisible(false);
            txtNombre.setText(descripcion);
        }
    }

    public void grabar() {
        if (txtNombre.getText().length() != 0) {
            if (opcion == 1) {
                String codigo = "", codigo_cortado = "";
                int nivel = Integer.parseInt(raiz_1), v1 = 0, longitud_caracteres = 0;
                v1 = nivel * 2 - 1;
                longitud_caracteres = nivel * 2;
                codigo_cortado = nivel_codigo.substring(0, (longitud_caracteres - 2));

                if (bd.verif_repite("SELECT idnivel FROM partida_nivel where nombre='" + txtNombre.getText() + "' and idnivel like '" + codigo_cortado + "%' and CHARACTER_LENGTH(idnivel)=" + longitud_caracteres + ";") == true) {
                    javax.swing.JOptionPane.showMessageDialog(null, "El nombre de la categoria ya existe");
                    return;
                }
                //System.out.println("***********" + raiz_1);

                codigo = metodos.generarCodigollaves("select substring(idnivel," + v1 + "," + longitud_caracteres + ") from partida_nivel where CHARACTER_LENGTH(idnivel)=" + longitud_caracteres + " order by substring(idnivel," + v1 + "," + longitud_caracteres + ") desc LIMIT 1 ", 2);
                codigo = codigo_cortado + codigo;
                bd.insert("partida_nivel", "idnivel, nombre, nivel, estado", "'" + codigo + "','" + txtNombre.getText() + "','" + (nivel) + "','A'");
            } else {
                bd.update("partida_nivel", "nombre='" + txtNombre.getText() + "'", "idnivel='" + nivel_codigo + "'");
            }

            dispose();
        } else {
            javax.swing.JOptionPane.showMessageDialog(null, "Ingrese el nombre");
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtDentroDe = new javax.swing.JTextField();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Grupo de partidas");

        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setText("Nombre:");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 50, 60, 25));

        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreKeyTyped(evt);
            }
        });
        jPanel1.add(txtNombre, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 50, 220, -1));

        jLabel2.setText("Dentro de:");
        jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 60, 25));

        txtDentroDe.setEditable(false);
        txtDentroDe.setHorizontalAlignment(javax.swing.JTextField.LEFT);
        jPanel1.add(txtDentroDe, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 20, 220, -1));

        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });
        jPanel1.add(btnAceptar, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 90, -1, -1));

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        jPanel1.add(btnCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 90, -1, -1));

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_dialog.jpg"))); // NOI18N
        jPanel1.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 330, 130));

        jLabel3.setText("nombre");
        jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 50, 60, -1));
        jPanel1.add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 50, 220, -1));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        grabar();
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void txtNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyTyped
        if (evt.getKeyChar() == 10) {
            grabar();
        }
    }//GEN-LAST:event_txtNombreKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlgIndiceEditar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlgIndiceEditar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlgIndiceEditar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlgIndiceEditar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                dlgIndiceEditar dialog = new dlgIndiceEditar(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField txtDentroDe;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables
}
